import { EResType } from "../../Common/Enum";
import EventID from "../../Common/EventID";
import Message from "../../Common/Message";
import GameUtil from "../../Util/GameUtil";
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM, GAME_TYPE_ENUM } from "../base/EnumIndex";
import { Tools } from "../common/Tools";
import { AudioManager1 } from "../manager/AudioManager1";
import { EventManager } from "../manager/EventManager";
import { NetworkManager } from "../manager/NetworkManager";
import { ResManager1 } from "../manager/ResManager1";
import { UIManager } from "../manager/UIManager";
import { AdBase } from "./AdBase";
import { AdManager } from "./AdManager";
const tt = window['tt'];
export class AdManager_ZJ extends AdBase {
    static get ins() {
        return super.getInstance<AdManager_ZJ>();
    }
    /** appID */
    app_id: string = "tt474e31f3d879811a02";
    /** 插屏ID */
    ad_inter_id: string = "";
    /** 激励ID   */
    ad_video_id: string = "ec0d1hegkhb1khmjbm";
    /** bannerID */
    ad_banner_id: string = "";

    ad_video3: any = null;  //3次视频广告;

    /** 巨量广告ClickID */
    clickID: string = null;
    /**直投项目id(当点击广告进来时和clickid一起拿到)*/
    projectId: string = null;
    /**广告id(当点击广告进来时和clickid一起拿到) */
    promotionId: string = null;
    /**直投参数 */
    cliKey: string = null;
    /**视频上报接口返回的数据用于结束视频上报接口 */
    levelKey: string = null;
    /** 巨量点击广告次数 */
    clickVideoNum: number = 0;

    isRank: boolean = false;     //是否启用排行榜功能

    /** 字节免费广告次数 */
    private freeAdNum: number = 0;
    public fuFangFinished: boolean = false;

    /**临时登录凭证 有效期3min */
    code: string = null;
    /**当前游戏id(文服字节为3) */
    gameId: number = 0;
    /**游戏类型（1微信 2抖音） */
    queryGameType: number = 2;
    /**用户openId */
    openId: string = null;

    /** 加载或者初始化所有广告 */
    loadAllAd() {
        switch (this.gameType) {
            case GAME_TYPE_ENUM.WO_YAO_BIAN_TU_LE:
                // this.ad_video_id = "24bs275tri4127e1fe";
                // this.gameName = "我要变秃了";
                // this.gameId = 4;
                // this.queryGameType = 2;
                // this.ad_video_id = "9egbb6il9go63l0he0";
                // this.gameName = "我要回老家";
                // this.gameId = 0;
                // this.queryGameType = 0;
                break;
            case GAME_TYPE_ENUM.NAO_DONG_TIAN_HUA_BAN:
                this.ad_video_id = "ec0d1hegkhb1khmjbm";
                this.gameName = "开始逆袭吧";
                this.gameId = 0;
                this.queryGameType = 0;
                break;
            case GAME_TYPE_ENUM.WEN_ZI_WO_FU_LE:
                // this.ad_video_id = "enhf1rh8y7p1h856g7";
                // this.gameName = "文字我服了";
                // this.gameId = 3;
                this.ad_video_id = "3jee3g5hkiad5h3msd";
                this.gameName = "整活大行家";
                this.gameId = 8;
                // this.ad_video_id = "f8jbb6idl36a2a115e";
                // this.gameName = "这波我很秀";
                // this.gameId = 13;
                this.queryGameType = 2;
                break;
            case GAME_TYPE_ENUM.WAN_DAN_ZHANG_NAO_ZI_LE:
                // this.ad_video_id = "1jsh9vriw8n4d8l7ea";
                // this.gameName = "完蛋长脑子了";
                // this.gameId = 6;
                // this.queryGameType = 2;
                this.ad_video_id = "73d90bh048a91075mc";
                this.gameName = "勇士战斗吧";
                this.gameId = 0;
                this.queryGameType = 0;
                break;
            case GAME_TYPE_ENUM.Luan_DOU_DA_BI_PIN:
                this.ad_video_id = "j5284gkog091ktmerv";
                this.gameName = "乱斗大比拼";
                this.gameId = 10;
                this.queryGameType = 2;
                break;
        }
        AdManager.gameId = this.gameId;
        AdManager.queryGameType = this.queryGameType;
        this.updateVersion();

        this.sysInfo = tt.getSystemInfoSync();
        this.initFreeAds();
        // this.initBanner();
        this.initVideoAd();

        /** 获取启动参数 */
        var options = tt.getLaunchOptionsSync();
        console.log("options:", options);
        if (options.query["clickid"]) {
            this.clickID = options.query["clickid"];
            AdManager.clickID = this.clickID;
            this.projectId = options.query["projectid"] || null;
            AdManager.projectId = this.projectId;
            this.promotionId = options.query["promotionid"] || null;
            AdManager.promotionId = this.promotionId;
            this.cliKey = options.query["ad_id"];
            AdManager.cliKey = options.query["ad_id"];
            // Tools.setStorage("juLiangClickID",this.clickID);
        } else {
            // this.clickID = Tools.getStorage("juLiangClickID");
        }

        // if (this.isRank) {
        let self = this;
        tt.login({
            force: true,
            success(res) {
                console.log("login 调用成功", res);
                self.code = res.code;
                if (self.gameId != 0) {
                    NetworkManager.getOpenId(self.gameId, self.queryGameType, self.code, (openId) => {
                        self.openId = openId;
                        NetworkManager.reportGameTime(self.gameId, openId, 1, self.clickID, self.queryGameType, self.projectId, null);
                    });
                }
            },
            fail(res) {
                console.log("login 调用失败", res);
            },
        });
        // }

        /**监听小游戏隐藏到后台的事件。锁屏、按 HOME 键退到桌面等操作会触发此事件。 */
        if (this.gameId != 0) {
            tt.onHide(() => {
                NetworkManager.reportGameTime(self.gameId, self.openId, 2, self.clickID, self.queryGameType, self.projectId, null);
            });
            tt.onShow(() => {
                NetworkManager.reportGameTime(self.gameId, self.openId, 1, self.clickID, self.queryGameType, self.projectId, null);
            })
        }
    };
    /** 复访相关初始化 */
    private initFreeAds() {
        this.fuFangFinished = Tools.getStorage("fuFangFinished");
        this.freeAdNum = Tools.getStorage("freeAdNum");
        if (this.freeAdNum === null) {
            this.freeAdNum = 0;
        }
        // console.log("复访", this.fuFangFinished, this.freeAdNum)
    }
    /** 复访 */
    public fuFang() {
        this.fuFangFinished = true;
        Tools.setStorage("fuFangFinished", true);
        // this.addFreeAds(1);

        // 加10000奖励
        // const gameData = StorageUtil.instance.getGameData();
        GameUtil.instance.changeResValue(EResType.Money, 10000);
        Message.instance.send(EventID.REFRESH_TOP_BAR, { type: EResType.Money, value: 10000 });
    }
    /**签到 */
    public sign(num) {
        this.freeAdNum = Tools.getStorage("freeAdNum");
        this.addFreeAds(num);
    }
    /**是否完成签到 */
    private isFinishSign() {
        let data = Tools.getStorage("signData", true);
        // if (data && data.length >= 7) {
        // return true;
        // }
        return false;
    }
    /** 添加免视频广告次数 */
    private addFreeAds(num: number) {
        this.freeAdNum += num;
        Tools.setStorage("freeAdNum", this.freeAdNum);
        // console.log("addFreeAds", this.freeAdNum)
    }
    /** 导航到侧边栏 */
    navigateToScene(callBack: Function) {
        tt.navigateToScene({
            scene: "sidebar",
            success: (res: any) => {
                console.log("navigate to scene success");
                // 跳转成功回调逻辑
                callBack();
            },
            fail: (res: any) => {
                console.log("navigate to scene fail: ", res);
                // 跳转失败回调逻辑
            },
        });
    }
    /** 是否是从侧边栏 进入游戏 */
    isFromSideBar(callBack: Function) {
        tt.onShow((res: any) => {
            console.log("启动参数：", res.query);
            console.log("来源信息：", res.refererInfo);
            console.log("场景值：", res.scene);
            console.log("启动场景字段：", res.launch_from, ", ", res.location);
            if ((res.launch_from == "homepage" && res.location == "sidebar_card")) {
                console.log("从侧边栏进入小游戏");
                callBack();
            } else {

            }
        });
    }
    /** 是否是抖音APP */
    private isDouyinApp() {
        return this.sysInfo.appName == "Douyin" || this.sysInfo.appName == "douyin_lite";
    }
    /** 初始化加载 视频广告 */
    private initVideoAd() {
        let self = this;
        this.ad_video = tt.createRewardedVideoAd({
            adUnitId: self.ad_video_id,
        });

        this.ad_video.onLoad(() => {
            console.log("视频广告加载完成!");
        });
        this.ad_video.load();
        this.ad_video.onClose((res: any) => {
            this.videoCallBack(res);
        });
    };
    videoCallBack(res: any) {
        if (res.isEnded || res.count) {
            console.log("获取奖励:", res)
            this.finishVideo();
            if (this.clickID) {   //巨量广告  两次回传
                this.clickVideoNum++;
                if (this.clickVideoNum == 2) {
                    NetworkManager.send_JuLiang("game_addiction", this.clickID)
                }
            }
        } else {
            console.log("没有观看完毕--");
            this.showModal("未观看完视频", "观看完视频才能获得奖励哦", () => {
                this.showVideoAd(this.videoBack, this.errorBack)
            }, () => {
                this.errorVideo();
            });
        }
    }
    /** 初始化加载 banner */
    private initBanner() {
        let self = this;
        var bannerData = {
            left: this.sysInfo.screenWidth,//广告位区域左上角横坐标
            top: this.sysInfo.screenHeight,//广告位区域左上角纵坐标
            width: this.sysInfo.screenWidth,//广告位区域宽度
        }

        this.ad_banner = tt.createBannerAd({
            adUnitId: self.ad_banner_id,
            adIntervals: 20,
            style: bannerData,
        });
    };
    /** 显示Banner广告 */
    public showBanner() {
        if (!this.ad_banner) {
            this.initBanner();
            // return;
        };

        if (this.ad_banner.show) {
            this.ad_banner.show();
        }

        this.ad_banner.onLoad(() => {
            this.ad_banner.show().then(() => {
                console.log("广告显示成功");
            }).catch((err: any) => {
                console.log("广告组件出现问题", err);
                this.ad_banner = null;
            });
        });
    };
    /** 隐藏Banner广告 */
    public hideBanner() {
        if (!this.ad_banner) { return; }
        this.ad_banner.hide();
    };
    /** 播放插屏广告 */
    public showIntersAd() {
        let self = this;
        var interstitialAd = tt.createInterstitialAd({
            adUnitId: self.ad_inter_id,
        });
        interstitialAd.load()
            .then(() => {
                interstitialAd.show().then(() => {
                    console.log("插屏广告展示成功");
                });
            }).catch((err: any) => {
                console.log(err);
            });
        console.log("showIntersAd");
    }
    /** 播放视频广告  成功回调   失败回调 */
    public showVideoAd(finishBack?: Function, errorBack?: Function, countNum?: number, canCostFreeNum: boolean = true) {
        this.videoBack = null;
        this.errorBack = null;
        if (finishBack) {
            this.videoBack = finishBack;
        } if (errorBack) {
            this.errorBack = errorBack;
        }


        if (this.freeAdNum > 0 && canCostFreeNum) {
            // console.log("复访免广告1次")
            this.addFreeAds(-1);
            if (this.videoBack) {
                this.videoBack();
            }
            return;
        }

        let self = this;
        if (countNum) {
            this.ad_video3 = tt.createRewardedVideoAd({
                adUnitId: self.ad_video_id,
                multiton: true,
                multitonRewardTimes: 3,
                progressTip: true
            });
        } else {
            this.ad_video = tt.createRewardedVideoAd({
                adUnitId: self.ad_video_id,
            });
        }

        this.ad_video.show().then(() => {
            console.log("广告显示成功");
        }).catch((err: any) => {
            this.errorVideo();
            console.log("广告组件出现问题", err);
        });
    }
    /** 视频播放完成 */
    finishVideo() {
        AudioManager1.resumeMusic();
        switch (this.gameType) {
            //我要变秃了 视频上报接口
            case GAME_TYPE_ENUM.WO_YAO_BIAN_TU_LE:
                // case GAME_TYPE_ENUM.WAN_DAN_ZHANG_NAO_ZI_LE:
                // lt_sdk.lt_network.zjReport()
                break;
            // case GAME_TYPE_ENUM.Luan_DOU_DA_BI_PIN:
            //     zs_sdk.zs_dyzt.checkVideoReport(true);
            //     break;
            default:
                break;
        }
        if (this.videoBack) {
            this.videoBack();
        }
        this.videoBack = null;
        this.errorBack = null;
    }
    /** 视频播放失败 isOut 是否中途退出*/
    errorVideo() {
        AudioManager1.resumeMusic();
        // switch (this.gameType) {
        //     case GAME_TYPE_ENUM.Luan_DOU_DA_BI_PIN:
        //         zs_sdk.zs_dyzt.checkVideoReport(false);
        //         break;
        //     default:
        //         break;
        // }
        if (this.errorBack) {
            this.errorBack();
        }
        this.videoBack = null;
        this.errorBack = null;
    };

    /** 开始录屏 */
    createVideoScreen() {
        if (this.videoTimer !== null) {
            clearTimeout(this.videoTimer);
            this.videoTimer = null;
        }
        var self = this;

        this.recorder = tt.getGameRecorderManager();
        this.recorder.onStart((s: any) => {
            console.log("开始录屏:", s);
        });
        this.recorder.onError((s: any) => {
            console.log("录屏错误:", s);
        });
        this.recorder.start({
            duration: 300
        });

        this.videoTimer = setTimeout(() => {
            self.stopVideoScreen();
        }, 1000 * 280);  //280s 后停止录屏
    };
    /** 停止录屏 */
    stopVideoScreen() {
        if (this.videoTimer !== null) {
            clearTimeout(this.videoTimer);
            this.videoTimer = null;
        }
        var self = this;

        console.log(this.recorder)
        if (!this.recorder || !this.recorder.stop) { return; }

        this.recorder.onStop((s: any) => {
            self.videoPath = s.videoPath;
        });
        this.recorder.stop();
    };
    /** 分享视频 */
    shareScreenVideo() {
        // shareTopics 分享话题  shareTitle 分享内容
        let shareTopics = [this.gameName];
        let shareTitle = this.gameName;

        var self = this;
        tt.shareAppMessage({
            channel: 'video',
            title: shareTitle,
            imageUrl: '',
            query: '',
            extra: {
                videoPath: self.videoPath, // 可用录屏得到的视频地址
                videoTopics: shareTopics
            },
            success() {
                EventManager.ins.emit(EVENT_NAME_ENUM.SHARE_SUCESS);  //抛出分享成功的事件
                console.log('分享视频成功');
            },
            fail(e: any) {
                if (e.errMsg == "shareAppMessage:cancel") {
                    return;
                }
                tt.showToast({
                    title: "录屏时间少于3s，分享失败！",
                    icon: "none",
                    duration: 2000,
                });
                console.log('分享视频失败', e);
            }
        });
        console.log("shareScreenVideo")
    };
    /** 分享给好友 */
    async shareFriends() {
        console.log("shareFriends")
        let shareTitle = this.gameName;
        let asset = await ResManager1.ins.loadRes("texture/share", cc.Asset, BUNDLE_TYPE_ENUM.HOME);
        tt.shareAppMessage({
            title: shareTitle,
            desc: "快来和我一起玩吧!",
            imageUrl: asset.url,
            query: "",
            success() {
                console.log("分享成功");
            },
            fail(e: any) {
                tt.showToast({
                    title: '分享失败',
                    icon: 'none',
                    duration: 1500//持续的时间
                })
                console.log("分享失败", e);
            },
        });
    };
    moreGamePanel: any = null;
    /** 添加更多游戏 */
    showMoreGame() {
        var self = this;
        if (!this.isDouyinApp()) { return; }
        if (!this.isBigVersion(this.sysInfo.SDKVersion, "2.82.0")) { return; }

        if (this.moreGamePanel) {
            return this.moreGamePanel.show();
        }
        try {
            console.log("添加更多游戏", "showMoreGame");
            self.moreGamePanel = tt.createGridGamePanel({
                gridCount: 'four',  // 'four', 'two' 'one'
                size: "large",
                query: {   //Json 格式
                    'tt80a1f61c1f9ffe0d02': 'age=1&name=文字我服了',
                    'tt6a581ce5f567fc8d02': 'age=2&name=编剧大湿',
                    'tt01a977149e96b55202': 'age=3&name=文字玩出花'
                },
            });
        } catch (error) {
            console.error("创建游戏推荐组件失败", error);
        };
        setTimeout(() => {
            if (self.moreGamePanel) {
                self.moreGamePanel.show();
            }
        }, 1000);
    };
    /** 隐藏更多游戏 */
    hideMoreGame() {
        if (this.moreGamePanel) {
            console.log("隐藏更多游戏");
            this.moreGamePanel.hide();
        }
    };

    checkScene(callback: Function) {
        // if (this.gameType == GAME_TYPE_ENUM.NAO_DONG_TIAN_HUA_BAN) {
        //     if (this.fuFangFinished || !tt.checkScene || !this.isOpenFuFang()) {
        //         callback(false);
        //         return;
        //     }
        // }
        if (!tt.checkScene || !this.isOpenFuFang()) {
            callback(false);
            return;
        }
        tt.checkScene({
            scene: "sidebar",
            success: (res: any) => {
                console.log("check scene success: ", res.isExist);
                // callback();

                //成功回调逻辑
                if (res.isExist) {
                    // if (this.gameType == GAME_TYPE_ENUM.NAO_DONG_TIAN_HUA_BAN) {
                    //     callback(!this.fuFangFinished)
                    //     return;
                    // }
                    // callback(!this.fuFangFinished || !this.isFinishSign());
                    callback(!this.fuFangFinished);
                } else {
                    callback(false)
                }
            },
            fail: (res: any) => {
                console.log("check scene fail:", JSON.stringify(res));
                //失败回调逻辑
                callback(false)
            }
        });
    }
    /** 是否是支持复访 */
    isOpenFuFang() {
        if (this.isBigVersion(this.sysInfo.SDKVersion, "2.92.0"))
            return true;
        return false;
    }

    /** 添加桌面功能 */
    addTable(call: Function) {
        tt.addShortcut({
            success: function (res: any) {
                console.log("添加桌面成功！", res);
                call();
                Tools.setStorage('zjaddShortcut', true);
            },
            fail: function (res: any) {
                console.log("添加桌面失败！", res);
            }
        });
    }
    /** 是否已经添加过桌面了 */
    isAddTable(callB: Function) {
        if (cc.sys.os === cc.sys.OS_ANDROID && this.isDouyinApp()) {
            //仅 Android 支持
            tt.checkShortcut({
                success: function (res: any) {
                    console.log(res.status);
                    if (res.status.exist) {
                        callB(false);
                        // if (res.status.needUpdate) {
                        //     callB(true);
                        // } else {
                        //     callB(false);
                        // }
                    } else {
                        callB(true);
                    }
                },
                fail: function (res: any) {
                    console.log("添加桌面fail:", res)
                    callB(true);
                }
            });
        } else {
            let isAdd = Tools.getStorage('zjaddShortcut');
            callB(!isAdd);
        }
    }

    /**订阅消息功能 */
    addSubscribe() {
        if (!this.isDouyinApp()) { return; }
        const tmplIds = ["MSG1469541137157322840271878900019"];
        tt.requestSubscribeMessage({
            tmplIds: tmplIds,
            complete: (res) => {
                if (res.errMsg == "requestSubscribeMessage:ok") {
                    Tools.setStorage('subscribe', true);
                }
            },
        });
    }

    showFavoriteGuide(callback: Function) {
        tt.showFavoriteGuide({
            type: "bar",
            content: "一键添加到我的小程序",
            position: "bottom",
            success(res) {
                console.log("引导组件展示成功");
            },
            fail(res) {
                if (res.errNo == 10401) {
                    UIManager.ins.showToast("已添加至我的收藏列表")
                }
                console.log("引导组件展示失败", res);
            },
        });
    }
    /** 弹框  确定或者取消 */
    showModal(titleStr: string, infoStr: string, finishBack?: any, cancelBack?: any) {
        tt.showModal({
            title: titleStr,
            content: infoStr,
            success(res: any) {
                if (res.confirm) {
                    if (!finishBack) { return; }
                    finishBack();
                    console.log("showModal, 确定");
                } else if (res.cancel) {
                    if (!cancelBack) { return; }
                    cancelBack();
                    console.log("showModal, 取消");
                }
            },
            fail(res: any) {
                console.log(`showModal调用失败` + res);
            },
        });
    }
    /** 震动 */
    vibrate(num: number) {
        if (num >= 15) {
            tt.vibrateLong({
                success(res: any) { console.log(res) },
                fail(res: any) { console.log(`vibrateLong调用失败:` + res); },
            });
        } else {
            tt.vibrateShort({
                success(res: any) { console.log(res) },
                fail(res: any) { console.log(`vibrateShort调用失败:` + res); },
            });
        }
    }
    /** 获取 游戏排行榜 */
    getRankList() {
        tt.getImRankList({
            relationType: "default", //好友榜、总榜都展示
            dataType: 0, //只圈选type为枚举类型的数据进行排序
            rankType: "week", //每天凌晨0点更新，只对当天0点到现在写入的数据进行排序
            suffix: "关", //为空或不填，一般枚举类型不需要填后缀
            rankTitle: "每周排行榜", //标题
            success(res: any) {
                console.log("getImRankData:", res);
            },
            fail(res: any) {
                console.log("getImRankData fail res:", res);
            },
        });

    };
    /** 上传排行榜分数 */
    setRankData(score: number) {
        if (!this.isDouyinApp()) { return; }
        tt.setImRankData({
            dataType: 0, //成绩为数字类型
            value: score.toString(), //该用户得了999999分
            priority: 0, //dataType为数字类型，不需要权重，直接传0
            extra: "extra",
            success(res) {
                console.log("setImRankData success:", res);
            },
            fail(res) {
                console.log("setImRankData fail:", res);
            },
        });
    };


    /** 是否要更新版本 */
    updateVersion() {
        const updateManager = tt.getUpdateManager();
        updateManager.onUpdateReady((res: any) => {
            tt.showModal({
                title: "更新提示",
                content: "新版本已经准备好，是否重启小游戏？",
                success: (res: any) => {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate();
                    }
                },
            });
        });
        updateManager.onUpdateFailed((err) => {
            console.log("版本下载失败原因", err);
            tt.showToast({
                title: "新版本下载失败，请稍后再试",
                icon: "none",
            });
        });
    };
}